<?php


namespace Beerus\Modules\BrandActivity\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel;
use Biz\model\springHomeDecActivity\ActivityProduct as mActivityProduct;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class ProductController extends Controller
{
    const  PAGE_SIZE = 20;

    public function index(Request $request, Content $content): Content
    {
        $request_data = $request->all();
        $condition = self::getCondition($request_data);
        $page_size = $request->input("per_page", self::PAGE_SIZE);
        $page = $request->input("page", 1);
        $where = $condition;
        $where['LIMIT'] = [
            ($page - 1) * $page_size,
            $page_size,
        ];
        $list = mActivityProduct::dataSelect($where);
        unset($where['LIMIT']);
        $total = mActivityProduct::dataCount($where);
        $gridModel = new GridDataModel($list, $total, [
            'perPage' => $page_size,
        ]);
        $grid = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->filter(function ($filter) {
                    // 在这里添加字段过滤器
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('product_id', '商品ID')->placeholder('商品ID');
                    });

                    $filter->expand();//默认展开
                });
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableActions();
                $grid->column('id', '主键ID');
                $grid->column('product_id', '商品ID');
                $grid->column('product_name', '名称')->width(120)->editable();
                $grid->column('product_type', '类型')->display(function ($product_type){
                    $v = [1=>'商品',2=>'服务'];
                    return $v[$product_type] ?? '';
                });
                $grid->column('product_pic', '图片')->width(150)->editable();
                $grid->column('product_value', '价值')->editable();
                $grid->column('total', '商品总量')->editable();
                $grid->column('num', '数量')->editable();
                $grid->column('status', '状态')->editable();
                $grid->column('is_show', '是否展示')->editable();
                $grid->column('create_time', '创建时间');

            });

        $tab = new Tab();
        $tab->add('活动商品列表', $grid->render(), true);
        $content->row($tab);

        return $content
            ->header('活动商品列表')
            ->description(' ')
            ->breadcrumb(['text' => '活动商品列表', 'url' => '/brandActivity/sproduct']);
    }

    private static function getCondition($request): array
    {
        $condition = [];
        if (isset($request['id']) && !empty($request['id'])) {
            $condition['id'] = $request['id'];
        }
        if (isset($request['product_id']) && !empty($request['product_id'])) {
            $condition['product_id'] = $request['product_id'];
        }
        return $condition;
    }

    public function create(Content $content, Form $form): Content
    {
        $form->disableReset();
        $form->text('product_id', "商品ID")->required();
        $form->text('product_name', "商品名称")->required();
        $form->select('product_type', "商品类型")->options([1=>'商品',2=>'服务'])->default(1)->required();
        $form->text('product_pic', "商品图片")->required();
        $form->decimal('product_value', "商品价值")->required();
        $form->number('total', "商品总量")->default(0)->required();
        $form->select('is_show', "是否展示")->options(['否','是'])->default(1)->required();
        $form->confirm('确定创建吗？');

        $form->action('/admin/brandActivity/sproduct/save');
        return $content
            ->header('新增')
            ->description(' ')
            ->breadcrumb(
                ['text' => '活动商品列表', 'url' => '/brandActivity/sproduct'],
                ['text' => '新增']
            )
            ->row($form);
    }

    public function save(Request $request)
    {
        $params = $request->all();
        $data = [
            'product_id' => $params['product_id'],
            'product_name' => $params['product_name'],
            'product_type' => $params['product_type'],
            'product_pic' => $params['product_pic'],
            'product_value' => $params['product_value'],
            'total' => $params['total'],
            'num' => $params['total'],
            'status' => mActivityProduct::STATUS_NORMAL,
            'is_show' => $params['is_show'],
            'create_time' => date('Y-m-d H:i:s', time()),
            'update_time' => date('Y-m-d H:i:s', time()),
        ];
        $result = mActivityProduct::dataInsert($data);
        
        if ($result) {
            $success = new MessageBag([
                'title' => '成功',
            ]);
        } else {
            $error = new MessageBag([
                'title' => '添加失败',
            ]);
            return back()->with(compact('error'))->withInput();
        }
        return redirect('/admin/brandActivity/sproduct')->with(compact('success'));
    }

    public function editSave(Request $request, $id)
    {
        $params = $request->all();
        $name = $params['name'] ?? null;
        $value = $params['value'];
        if (!$name) {
            return response()->json([
                'message' => '操作失败',
                'status' => false,
            ]);
        }
        $data = [
            $name => $value,
            'update_time' => date('Y-m-d H:i:s', time()),
        ];
        mActivityProduct::dataUpdate($data, ['id' => $id]);
        $success = [
            'message' => '操作成功',
            'status' => true,
        ];
        return response()->json($success);
    }

}